package com.kanshu.ksgb.fastread.doudou.app.test

import android.app.Dialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.database.ContentObserver
import android.net.ConnectivityManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.util.Log
import android.view.*
import android.view.animation.AnimationUtils
import android.widget.CompoundButton
import android.widget.SeekBar
import com.alibaba.android.arouter.launcher.ARouter
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants
import com.kanshu.ksgb.fastread.doudou.app.test.DisplayUtils.*
import com.kanshu.ksgb.fastread.doudou.base.basemvp.BaseMVPActivity
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdUtils
import com.kanshu.ksgb.fastread.doudou.common.business.ad.ReaderAdHelper
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean
import com.kanshu.ksgb.fastread.doudou.common.business.event.ReaderFinishEvent
import com.kanshu.ksgb.fastread.doudou.common.business.event.ShelfEvent
import com.kanshu.ksgb.fastread.doudou.common.business.manager.CacheManager
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager
import com.kanshu.ksgb.fastread.doudou.common.business.routerservice.IMakeMoneyService
import com.kanshu.ksgb.fastread.doudou.common.business.utils.BookUtils
import com.kanshu.ksgb.fastread.doudou.common.net.INetCommCallback
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult
import com.kanshu.ksgb.fastread.doudou.common.util.*
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils
import com.kanshu.ksgb.fastread.doudou.common.view.CustomDialog
import com.kanshu.ksgb.fastread.doudou.module.book.adapter.BookmarkAdapter
import com.kanshu.ksgb.fastread.doudou.module.book.adapter.ReadThemeAdapter
import com.kanshu.ksgb.fastread.doudou.module.book.bean.*
import com.kanshu.ksgb.fastread.doudou.module.book.presenter.BookListPresenter
import com.kanshu.ksgb.fastread.doudou.module.book.presenter.BookPresenter
import com.kanshu.ksgb.fastread.doudou.module.book.retrofit.requestparams.ChapterRequestParams
import com.kanshu.ksgb.fastread.doudou.module.reader.bean.BookRecordBean
import com.kanshu.ksgb.fastread.doudou.module.reader.page.PageLoader
import com.kanshu.ksgb.fastread.doudou.module.reader.page.PageStyle
import com.kanshu.ksgb.fastread.doudou.module.reader.page.TxtChapter
import com.kanshu.ksgb.fastread.doudou.module.reader.presenter.ReadContract
import com.kanshu.ksgb.fastread.doudou.module.reader.presenter.ReadPresenter
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.ObtainAllSimpleChaptersHelper
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.ScreenOnHelper
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.SettingManager
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.ThemeManager
import com.kanshu.ksgb.fastread.doudou.module.reader.view.BookReadBottomLayout
import com.kanshu.ksgb.fastread.doudou.module.reader.view.BookReadErrorLayout
import com.qmuiteam.qmui.util.QMUINotchHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.activity_reader.*
import kotlinx.android.synthetic.main.layout_new_read_aa_set.*
import kotlinx.android.synthetic.main.layout_read_mark.*
import kotlinx.android.synthetic.main.layout_reader_brightness_set.*
import kotlinx.android.synthetic.main.layout_reader_progress_set.*
import kotlinx.android.synthetic.main.layout_top_menu_bar.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.lang.ref.WeakReference
import java.util.*
import java.util.concurrent.TimeUnit

class ReaderActivity : BaseMVPActivity<ReadContract.Presenter>(), ReadContract.View {

    // 外部传入参数
    val EXTRA_BOOK_ID = "book_id"
    val EXTRA_CHAPTER_ID = "content_id"
    val EXTRA_CHAPTER_INDEX = "order"
    val EXTRA_BOOK_NAME = "book_title"
    val EXTRA_JUMP_TO_HOME = "jump_to_home"
    val EXTRA_CONTINUE_READ = "continue_read"
    var ACTION_DESTORY = 9
    var mBookId: String? = null

    // 当前页面的状态
    val STATUS_LOADING = 1         // 正在加载
    val STATUS_FINISH = 2          // 加载完成
    val STATUS_ERROR = 3           // 加载错误 (一般是网络加载情况)
    val STATUS_EMPTY = 4           // 空数据
    val STATUS_PARING = 5          // 正在解析 (装载本地数据)
    val STATUS_PARSE_ERROR = 6     // 本地文件解析错误(暂未被使用)
    val STATUS_CATEGORY_EMPTY = 7  // 获取到的目录为空
    val STATUS_OFFLINE = 8         // 作品下架
    val STATUS_ERASE = 9           // 擦除
    var mStatus = STATUS_LOADING

    //章节总数
    var mChapterSum = 0
    // 章节内容id
    private var mChapterId: String? = null
    // 是否需要连续阅读
    private var mContinueRead: Boolean = false
    // 开始阅读标记 如果为true说明会渲染页面
    private var mStartRead: Boolean = false
    //当前章节序号
    private var mOrder = 1
    private var mBookTitle: String? = null
    private var mChapterTitle: String? = null
    private var mIsJumpToHome: Boolean = false
    // 是否第一次绘制文字信息
    private var mIsFirstRender: Boolean = false
    internal var mLifeCyclerSubject: Subject<Int> = PublishSubject.create()
    // 章节内容请求参数
    internal var mParams: ChapterRequestParams? = ChapterRequestParams()
    // 广告配置
    private var mShowAD: ADConfigBean? = null
    // 广告高度
    private var mAdHeight = 0
    private var mScreenHeight: Int = 0
    private var mScreenWidth: Int = 0
    // 广告是否加载成功  才showAD  默认设置为true  是为了第一次广告加载失败回调时可以关闭广告显示
    private var mLoadSuccShowAd = true
    // 主题色适配器
    lateinit var gvAdapter: ReadThemeAdapter
    // 当前主题
    private var mCurTheme: Int = 0
    // 主题列表
    lateinit var mReadThemes: List<ReadTheme>
    // 书签适配器
    var mMarkAdapter: BookmarkAdapter? = null
    // 书签列表
    lateinit var mMarkList: MutableList<BookMark>
    // 阅读器夜间模式变量
    private var isNightMode = false
    // 亮度监听器
    private var mLightnessObserver: ContentObserver? = null
    //    private var mHandler: SafeHandler? = null
    // 阅读器分页管理器
//    private var mPageLoader: PageLoader? = null
    // 用于阅读器上报阅读记录
    private var mListPresenter: BookListPresenter? = null
    // 屏幕常亮工具类
    private var mScreenOnHelper: ScreenOnHelper? = null
    // 点击记录时间戳
    private var sClickTime1 = 0L
    //阅读器视频播放辅助类
    var mReaderAdHelper: ReaderAdHelper? = null
    // 错误处理页面
    var mErrorLayout: BookReadErrorLayout? = null
    // 判断是否后台记录了已经加入书架
    private var mJoinShelfFromServer: Boolean = false
    private var mOldTime: Long = 0
    private var mCurrentChapterPos: String? = ""
    // 当前章节内容页数
    private var mCurrentChapterCount: Int = 0
    // 章节进度 监听 章节内容页数;
    private var mSeekbarListenerPageCount: Int = 0
    private var mCurrentAdHeightMode: Int = 0   // 当前广告高度模式
    // 存储阅读记录类
    private var mBookRecord: BookRecordBean? = null
    var data = mutableListOf<ReaderItem>()
    lateinit var readerAdapter: ReaderAdapter
    //当前章节简单信息
    var mChapterNode: SimpleChapterBean? = null
    var mLastChapterNode: SimpleChapterBean? = null
    var mNextChapterNode: SimpleChapterBean? = null
    var llLayoutManager: LinearLayoutManager? = null
    var lastItem: ReaderItem? = null

    //记录退出阅读器时顶部段落所在的章节序号（order）,及段落位置（pos）
    var mRecordOrder = 1
    var mTopItemPos = 0

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        parseData()
        mScreenHeight = DisplayUtils.getScreenHeight(this) + MMKVDefaultManager.getInstance().notchHeight
        mScreenWidth = DisplayUtils.getScreenWidth(this)
        mAdHeight = resources.getDimensionPixelSize(R.dimen.px_150)
        mListPresenter = BookListPresenter(null)
        // 屏幕常亮工具类
        mScreenOnHelper = ScreenOnHelper(this)
        //获取阅读器视频播放辅助类并记录开始阅读时间
        mReaderAdHelper = ReaderAdHelper(this)
        mReaderAdHelper?.startReadTime()
//        mAdTimerHelper.startTimer()
    }

    /**
     * 解析外部传入的参数
     */
    private fun parseData() {
        // 支持scheme模式
        val uri = intent.data
        if (uri == null) {
            parseIntent()
            return
        }
        if (uri.isOpaque) {
            parseVipJpushChannel()
        } else {
            val names = uri.queryParameterNames
            if (names != null && names.size > 0) {
                for (name in names) {
                    if (!TextUtils.isEmpty(name)) {
                        val value = uri.getQueryParameter(name)
                        intent.putExtra(name, value)
                    }
                }
            }
            parseIntent()
        }
        SettingManager.getInstance().saveReadBook(mBookId, true)
    }

    override fun getContentId(): Int {
        return R.layout.activity_reader
    }

    override fun initWidget() {
        super.initWidget()

        llLayoutManager = LinearLayoutManager(this)
        mPageLoader.layoutManager = llLayoutManager
        readerAdapter = ReaderAdapter(this, data)
        mPageLoader.adapter = readerAdapter
        mPageLoader.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //向上滑动，首个可见条目order和上一个不一致时，向上跳章
                //向下滑动，最后一个可见条目和下一个不一致时，向下跳章
                var lastPos = llLayoutManager!!.findLastVisibleItemPosition()
                var firstVisiblePos = llLayoutManager!!.findFirstVisibleItemPosition()
                var mid = (lastPos + firstVisiblePos) / 2

                if (!loadingData && mid > -1 && mid < data.size) {
                    if (lastItem == null) {
                        lastItem = data[mid]
                    } else if (lastItem?.order != data[mid].order) {
                        //update chapter node
                        lastItem = data[mid]
                        updateOrder(data[mid].order)
                    }
                }
                if (firstVisiblePos > -1 && firstVisiblePos < data.size) {
                    mRecordOrder = data[firstVisiblePos].order
                    mTopItemPos = data[firstVisiblePos].itemPos
                }
            }
        })

        // 初始化阅读器引导页
        val entryReader = SettingManager.getInstance().isFirstEntryReader
        // 获取到夜间模式状态
        isNightMode = SettingManager.getInstance().isNight
        reader_guide.setVisibility(if (entryReader) View.VISIBLE else View.GONE)
        //获取页面加载器
        mPageLoader.bookId = mBookId
        //设置字体显示结果
        font_result.setText(SettingManager.getInstance().readFontSize.toString())
        // 注册广播
        register()
        //隐藏StatusBar
        runOnUiThread { this.hideSystemBar() }
        //初始化阅读进度
        initReadProgress()
        //初始化TopMenu
        initTopMenu()
        //初始化BottomMenu
        initBottomMenu()
        //初始化音量键显示
        initVolume()
        // 初始化主题
        initTheme()
        //亮度模块初始化
        initBrightness()
        // 初始化翻页模式
//        initPageMode()
        // 初始化屏幕常亮参数
        initScreenOnParams()
    }

    /**
     * 计算字体大小
     *
     * @param progress
     */
    private fun calcFontSize(dpValue: Int) {
        if (dpValue < 12 || dpValue > 36) {
            return
        }
        font_result.text = dpValue.toString()
        SettingManager.getInstance().saveFontSize(dpValue)
        readerAdapter.setFontSize()
    }


    /**
     * 作用：设置与文字相关的参数
     *
     * @param textSize
     */
    private fun setUpTextParams(textSize: Int) {
        // 文字大小
        readerAdapter.mTextSize = textSize
        // 存储文字大小
        SettingManager.getInstance().saveFontSize(textSize)
//        mTitleSize = mTextSize + DisplayUtils.dpToPx(EXTRA_TITLE_SIZE, mContext)
//        // 行间距(大小为字体的一半)
//        mTextInterval = mTextSize
//        mTitleInterval = mTitleSize / 2
//        // 段落间距(大小为字体的高度)
//        mTextPara = mTextSize
//        mTitlePara = mTitleSize + mTitleMarginTop
    }

    override fun initClick() {
        tvSettings.setOnClickListener {
            toggleReadBar(true)
        }
        reader_guide.setOnClickListener {
            gone(reader_guide)
            SettingManager.getInstance().saveFirstEntryReader(false)
        }

        tvFontsizeMinus.setOnClickListener {
            // 字体大小减少
            val s = font_result.text.toString().trim { it <= ' ' }
            val progress = Integer.parseInt(s)
            calcFontSize(progress - 1)
        }
        tvFontsizePlus.setOnClickListener {
            // 字体大小增加
            val s1 = font_result.text.toString().trim { it <= ' ' }
            val progress1 = Integer.parseInt(s1)
            calcFontSize(progress1 + 1)
        }
        tvClear.setOnClickListener {
            // 书签清除
            SettingManager.getInstance().clearBookMarks(mBookId)
            updateMark()
        }
        tvAddMark.setOnClickListener {
            // 添加书签
            addBookMark(true)
        }
        ivBack.setOnClickListener {
            gone(rlReadAaSet)
            //animInOrOut(mRlReadAaSet, true);
            hideReadBar()
            if (mIsJumpToHome) {
                ARouterUtils.toActivity(ARouterConfig.HOME_PAGE)
                finish()
                return@setOnClickListener
            }
            val flg = processJoinShelf()
            if (flg == 0) {
                finish()
            }
        }
        download.setOnClickListener {
            if (!MMKVUserManager.getInstance().isUserLogin) {
                ARouterUtils.toActivity(ARouterConfig.PERSONAL_LOGIN_IN, "phone", "")
            } else {
                ARouterUtils.toActivity(ARouterConfig.DOWNLOAD_DOWNLOAD_CHAPTER, "book_id", mBookId)
            }
        }

    }

    override fun bindPresenter(): ReadContract.Presenter {
        return ReadPresenter("1", mLifeCyclerSubject)
    }

    override fun showContent(chapterBean: BaseResult<ChapterBean>, load_type: Int) {
        if (BaseResult.isNotNull(chapterBean) && chapterBean.result.status != null) {
            val code = chapterBean.result.status.code
            val data = chapterBean.result.data
            if (data == null) {
                if (!TextUtils.isEmpty(chapterBean.result.status.msg)) {
                    ToastUtil.showMessage(chapterBean.result.status.msg)
                }
                if (code == Constants.ErrCode.Offline) {
                    // 下线标记
                    if (getPageStatus() == STATUS_LOADING) {
                        mPageLoader.bookOffline()
                        handleBookError(code)
                    }
                    return
                }
                // 显示加载失败
                if (getPageStatus() == STATUS_LOADING) {
                    mPageLoader.chapterError()
                    handleBookError(Constants.ErrCode.NetErr)
                }
                return
            }
            if (TextUtils.isEmpty(data.order)) {
                return
            }
            var orderIndex = data.order.toInt()
            Log.d("http", "pageIndex:(parse)$orderIndex")
            if (data.book_info != null) {
                // 存储当前书籍信息
                if (!mStartRead) {
                    DiskLruCacheUtils.put(mBookId + "simple", data.book_info, true)
                }
                // 从后台知道当前书籍是否收藏过
                mJoinShelfFromServer = TextUtils.equals("1", chapterBean.result.data.book_info.join_bookcase)
                //保存书籍分类和连载
                MMKVDefaultManager.getInstance().setBookAttribute(data.book_info.book_id, data.book_info.writing_process, data.book_info.category_id_1)
            }
            // 获取数据成功
            mChapterSum = Integer.parseInt(if (TextUtils.isEmpty(data.book_info.chapter_count)) "1" else data.book_info.chapter_count)
            // 保存章节总数
//            mChapterSum = count
            // 保存扉页信息
            if (orderIndex == 1) {
                setHeadpageInfo(data.cp_info)
            }
            // 做一定的调整(有可能后台给出错误的数据)
            if (orderIndex > mChapterSum) {
                orderIndex = mChapterSum
            }
            // 保存当前章节的简单信息
            SettingManager.getInstance().saveSimpleChapterInfo(mBookId, orderIndex, data)
            if (code == Constants.ErrCode.SUCCESS) {
                // 显示内容
                if (!TextUtils.isEmpty(data.content)) {
                    showChapterContent(data, orderIndex, load_type)
                } else {
                    // 显示数据为空
                    if (getPageStatus() == PageLoader.STATUS_LOADING) {
                        mPageLoader.chapterEmpty()
                    }
                }
            } else if (code == Constants.ErrCode.InsufficientBalance
                    || code == Constants.ErrCode.BuyToRead
                    || code == Constants.ErrCode.FailToConsumeByBalance) {
                if (orderIndex != mOrder) {
                    Log.d("http", "pageIndex:$orderIndex,mOrder$mOrder")
                    ToastUtil.showMessage("余额不足")
                    return
                }
                // 下载简单章节信息
                downloadSimpleChapter(orderIndex)
            } else {
                ToastUtil.showMessage(chapterBean.result.status.msg)
            }
        }
    }

    private fun setBookTitle() {
        tvBookName.text = mBookTitle
    }

    private fun setCurChapterTitle() {
        tvChapterName.text = mChapterTitle
    }

    override fun showError(contentId: String?, code: Int, desc: String?) {
        // 获取数据失败 处理各种状态码
        //ToastUtil.showMessage(getString(R.string.standard_net_tip));
        mPageLoader.visibility = View.GONE
        handleBookError(Constants.ErrCode.NetErr)
    }

    /**
     * 根据错误码处理阅读器页面
     *
     * @param code
     */
    private fun handleBookError(code: Int) {
        if (mErrorLayout == null) {
            val stub = findViewById<ViewStub>(R.id.err_stub)
            if (stub != null) {
                val v = stub.inflate()
                mErrorLayout = v.findViewById(R.id.err_handle_container)
            }
        }
        if (mErrorLayout != null) {
            mErrorLayout!!.setCallback(object : BookReadErrorLayout.ReadErrCallback {
                override fun onRetry() {
                    mStartRead = false
                    readContentByNetOrLocal()
                }

                override fun onTouch() {
                    toggleReadBar(true)
                }
            })
            mErrorLayout!!.refreshByErrorCode(code)
        }
    }

    /**
     * 解析外部传入的参数
     */
    private fun parseIntent() {
        var lastBookId: String? = mBookId
        mBookId = intent.getStringExtra(EXTRA_BOOK_ID)
        var notSameBook = !TextUtils.isEmpty(lastBookId) && !lastBookId.equals(mBookId)
        // 标记前后不是一本书
        if (notSameBook) {
            resetBookId()
        }
        // mChapterId为空则是第一个章节获取内容
        mChapterId = intent.getStringExtra(EXTRA_CHAPTER_ID)
        val order = intent.getStringExtra(EXTRA_CHAPTER_INDEX)
        if (!TextUtils.isEmpty(order)) {
            mOrder = Integer.parseInt(order)
        } else {
            mOrder = 1
        }
        mBookTitle = intent.getStringExtra(EXTRA_BOOK_NAME)
        val isJumpHome = intent.getStringExtra(EXTRA_JUMP_TO_HOME)
        if (!TextUtils.isEmpty(isJumpHome)) {
            mIsJumpToHome = java.lang.Boolean.parseBoolean(isJumpHome)
        }
        if (TextUtils.isEmpty(mBookTitle)) {
            mBookTitle = getBookTitle()
        }
        val continueRead = intent.getStringExtra(EXTRA_CONTINUE_READ)
        if (!TextUtils.isEmpty(continueRead)) {
            mContinueRead = java.lang.Boolean.parseBoolean(continueRead)
        }
        if (mContinueRead && mPageLoader != null) {
            // 根据上次的阅读记录去阅读
            mPageLoader.setChapterOpen(false)
        }
        mStartRead = false

        // 获取书签信息
        if (mMarkAdapter != null) {
            updateMark()
        }
//        }
        // 获取本书的简单章节信息
        ObtainAllSimpleChaptersHelper.getAllSimpleChaptersByForce(mBookId)
    }

    /** 打开章节类型
     *  LOAD_TYPE_INIT 初始化
     *  LOAD_TYPE_LAST 加载上一章
     *  LOAD_TYPE_NEXT 加载下一章
     **/
    val LOAD_TYPE_INIT = 0
    val LOAD_TYPE_LAST = 1
    val LOAD_TYPE_NEXT = 2
    @Synchronized
    private fun loadChapter(order: Int, skipType: Int) {
        loadingData = true
        when (skipType) {
            LOAD_TYPE_INIT -> ChapterLoadUtils.loadChapterContent(mBookId, order) { content, title ->
                ReaderItem.init()
                data.clear()
                mChapterTitle = title
                var items = getItems(content, order)
                var chapterName = ReaderItem(mBookId, order, 0, title)
                chapterName.isChapterName = true
                items.add(0, chapterName)
                data.addAll(items)
                runOnUiThread {
                    updateTitleInfo()
                    readerAdapter.notifyDataSetChanged()
                    scrollToRecordItem()
                    preloadLastAndNext(true)
                    loadingData = false
                }
            }

            LOAD_TYPE_NEXT -> ChapterLoadUtils.loadChapterContent(mBookId, order) { content, title ->
                var lastItem = data.lastOrNull()
                if (lastItem == null || order > lastItem.order) {
                    var items = getItems(content, order)
                    var chapterName = ReaderItem(mBookId, order, 0, title)
                    chapterName.isChapterName = true
                    var lastLen = data.size
                    items.add(0, chapterName)
                    runOnUiThread {
                        data.addAll(items)
                        var len = data.size
                        readerAdapter.notifyItemRangeInserted(lastLen, len)
                        mNextChapterNode = getSimpleChapterBean(order)
                        loadingData = false
                    }
                }
            }

            LOAD_TYPE_LAST -> ChapterLoadUtils.loadChapterContent(mBookId, order) { content, title ->
                var firstItem = data.firstOrNull()
                if (firstItem == null || order < firstItem.order) {
                    var items = getItems(content, order)
                    var chapterName = ReaderItem(mBookId, order, 0, title, true)
                    chapterName.isChapterName = true
                    items.add(0, chapterName)
                    runOnUiThread {
                        data.addAll(0, items)
                        var len = items.size
                        readerAdapter.notifyItemRangeInserted(0, len)
                        mLastChapterNode = getSimpleChapterBean(order)
                        loadingData = false
                    }
                }
            }
        }

    }

    private fun scrollToRecordItem() {
        mPageLoader.scrollToPosition(mTopItemPos)
        llLayoutManager?.scrollToPositionWithOffset(mTopItemPos, 0)
    }

    private fun updateTitleInfo() {
        mPageLoader.post {
            mChapterTitle = mChapterNode?.title
            if (TextUtils.isEmpty(mBookTitle)) {
                mBookTitle = mChapterNode?.book_title
            }
            tvBookName.text = mBookTitle
            tvChapterName.text = mChapterTitle
        }
    }

    var splitStr = "\r\n"
    fun getItems(chapterContent: String, order: Int): MutableList<ReaderItem> {
        if (TextUtils.isEmpty(chapterContent)) {
            return mutableListOf()
        }
        var res = mutableListOf<ReaderItem>()
        //合并多余的换行
        val content = chapterContent.replace("(\r\n)\\1+".toRegex(), "\r\n")
        var tmp = -1
        var searchStart = 0

        var pos = 1
        while (content.indexOf(splitStr, searchStart) != -1) {
            tmp = content.indexOf(splitStr, searchStart)
            var paraStr = content.substring(searchStart, tmp).trim()
            searchStart = tmp + 2
            println("CONTENT: $paraStr")
            res.add(ReaderItem(mBookId, order, pos++, paraStr))
        }
        if (searchStart < content.length) {
            val str = content.substring(searchStart, content.length)
            res.add(ReaderItem(mBookId, order, pos, str))
            println("CONTENT: $str")
        }
        res[res.size - 1].content += "\r\n\r\n\r\n\r\n"
        return res
    }


    /**
     * 更新书签
     */
    private fun updateMark() {
        if (mMarkAdapter == null) {
            mMarkAdapter = BookmarkAdapter(this, R.layout.item_read_mark, mMarkList)
            lvMark.setAdapter(mMarkAdapter)
            lvMark.setOnItemClickListener({ parent, view, position, id ->
                val mark = mMarkList.get(position)
                if (mark != null) {
                    mark.textSize = if (mark.textSize == 0) SettingManager.getInstance().readFontSize else mark.textSize
                    if (mark.position == 0 && mark.startPos > 0) {
                        // 兼容之前老阅读器的数据
                        mark.position = mark.startPos / 1000
                    }
                    if (mPageLoader != null) {
                        // 隐藏章节之间的广告
//                        DisplayUtils.gone(mAdBetweenChaptersLayout)
                        mPageLoader.skipToMark(mark.chapter, mark.position, mark.textSize)
                        // 兼容之前的老版本阅读器数据
                        if (mark.startPos > 0) {
                            // 移除之前的老的数据，用新的代替
                            SettingManager.getInstance().removeBookMarkForOldReader(mBookId, mark)
                            addBookMark(false)
                        }
                    }
                    llBookReadBottom.clearCheck()
                    hideSystemBar()
                    gone(rlReadAaSet, rlReadMark, llBookReadBottom, read_abl_top_menu)
                } else {
                    ToastUtil.showMessage("书签无效")
                }
            })
        }
        if (mMarkList != null) {
            mMarkList.clear()
        }
        var cache = SettingManager.getInstance().getBookMarks(mBookId)
        if (cache != null && cache.size > 0) {
            mMarkList.addAll(cache)
            Collections.reverse(mMarkList)
        }
        mMarkAdapter?.setData(mMarkList)
    }

    /**
     * 重置bookid
     */
    private fun resetBookId() {
        mStartRead = false
        mOrder = 1
        super.processLogic()
//        mPageLoader.resetBookId(mBookId)
    }

    /**
     * 读取章节内容从网络或者本地
     */
    private fun readContentByNetOrLocal() {
        if (CacheManager.getInstance().getChapterFile(mBookId, mOrder) != null) {
            // 从缓存中读取数据
            showChapterContent(null, mOrder, LOAD_TYPE_INIT)
        } else {
            val info = SettingManager.getInstance().getSimpleChapterInfo(mBookId, mOrder)
            if (info != null) {
                // 从网络获取
                mChapterId = info.content_id
                initChapterContent()
            } else {
                downloadSimpleChapter(mOrder, object : INetCommCallback<SimpleChapterBean> {
                    override fun onResponse(simpleChapterBean: SimpleChapterBean?) {
                        if (simpleChapterBean == null) {
                            return
                        }
                        mChapterNode = simpleChapterBean
                        mChapterId = simpleChapterBean.content_id
                        mOrder = simpleChapterBean.order.toInt()
                        initChapterContent()
                    }

                    override fun onError(code: Int, errDesc: String) {
                        if (getPageStatus() == PageLoader.STATUS_LOADING) {
                            mPageLoader.chapterError()
                            handleBookError(Constants.ErrCode.NetErr)
                        }
                    }
                })
            }
        }
    }

    /**
     * 显示章节内容
     * 如果是当前章，此时会进入阅读器
     *
     * @param content
     * @param order
     */
    private fun showChapterContent(chapter: ChapterBean?, order: Int, load_type: Int) {
        var content = chapter?.content
        // 先缓存内容
        if (!TextUtils.isEmpty(content)) {
            CacheManager.getInstance().saveChapterFile(mBookId, order, content)
        }
        // 第一次会调用以下代码
        val chapterFile = CacheManager.getInstance().getChapterFile(mBookId, order)
        if (!mStartRead && chapterFile != null) {
            // 隐藏错误页面
            DisplayUtils.gone(mErrorLayout)
            mStartRead = true
            // 設置章節總數
            mChapterSum = SettingManager.getInstance().getChapterCount(mBookId)
            mOrder = order
        }
        // 跳轉到指定章節 进入pageloader逻辑
        if (mOrder < mChapterSum) {
            loadChapter(order, load_type)
        }
    }

    @Synchronized
    @Throws(Exception::class)

            /**
             * 添加书签
             */
    fun addBookMark(showToast: Boolean) {
        if (mPageLoader == null) {
            return
        }
        val pageStatus = getPageStatus()
        if (pageStatus != PageLoader.STATUS_FINISH) {
            ToastUtil.showMessage("章节内容没有加载完成，不能添加书签")
            return
        }
        val mark = BookMark()
        mark.chapter = mOrder
        //todo
        mark.position = mPageLoader.getPagePos()
        mark.textSize = SettingManager.getInstance().readFontSize
        if (mark.chapter >= 1 && mark.chapter <= SettingManager.getInstance().getChapterCount(mBookId)) {
            mark.title = mPageLoader.getCurChapterTitle()
            if (TextUtils.isEmpty(mark.title)) {
                mark.title = SettingManager.getInstance().getCurBookChapterTitle(mBookId, mark.chapter)
            }
        }
        mark.desc = mPageLoader.getHeadLine()
        if (SettingManager.getInstance().addBookMark(mBookId, mark)) {
            if (showToast) {
                ToastUtil.showMessage("添加书签成功")
            }
            updateMark()
        } else {
            if (showToast) {
                ToastUtil.showMessage("书签已存在")
            }
        }
    }

    private fun showSystemBar() {
        //如果是刘海屏，则不做处理
        if (QMUINotchHelper.hasNotch(this)) {
            if (QMUINotchHelper.isNotchOfficialSupport()) {
                DisplayUtils.setTranslucent(this)
                SystemBarUtils.showUnStableStatusBar(this)
            } else {
                SystemBarUtils.hideStableStatusBar(this)
                return
            }
        } else {
            SystemBarUtils.showUnStableStatusBar(this)
            quitFullScreen()
        }
    }

    private fun hideSystemBar() {
        if (QMUINotchHelper.hasNotch(this)) {
            if (QMUINotchHelper.isNotchOfficialSupport()) {
                quitFullScreen()
                DisplayUtils.setTranslucent(this)
            }
        } else {
            //如果不是刘海屏,隐藏
            SystemBarUtils.hideStableStatusBar(this)
            setFullScreen()
        }
        if (llBookReadBottom != null)
            llBookReadBottom.clearCheck()
    }

    private fun setFullScreen() {
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
    }

    private fun quitFullScreen() {
        val attrs = window.attributes
        attrs.flags = attrs.flags and WindowManager.LayoutParams.FLAG_FULLSCREEN.inv()
        window.attributes = attrs
        window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
    }

    /**
     * 第一章的contentid为空
     * 根据章节id获取章节内容
     */
    private fun initChapterContent() {
        getChapterContent(mChapterId, ChapterRequestParams.UN_CACHED, LOAD_TYPE_INIT)
    }

    /**
     * 读取章节内容，如果为0则是正常读，1则是用于缓存数据
     *
     * @param content_id
     * @param is_cache
     */
    private fun getChapterContent(content_id: String?, is_cache: Int, load_type: Int) {
        val params = ChapterRequestParams()
        params.book_id = mBookId
        params.content_id = content_id
        params.is_cache = is_cache
        // 下一个章节的内容
        mPresenter.getChapterContent(params, load_type)
    }

    /**
     * 下载简单章节信息
     *
     * @param chapter
     */
    private fun downloadSimpleChapter(chapter: Int) {
        downloadSimpleChapter(chapter, null)
    }

    /**
     * 下载简单章节内容信息
     *
     * @param order
     * @param callback
     */
    private fun downloadSimpleChapter(order: Int, callback: INetCommCallback<SimpleChapterBean>?) {
        mPresenter.getSimpleChapterInfo(mBookId, order.toString() + "", object : INetCommCallback<SimpleChapterBean> {
            override fun onResponse(simpleChapterBean: SimpleChapterBean) {
                SettingManager.getInstance().saveSimpleChapterInfo(mBookId, order, simpleChapterBean)
                callback?.onResponse(simpleChapterBean)
            }

            override fun onError(code: Int, errDesc: String) {
                Log.d("wcy", "getSimpleChapterInfoByMMKV---")
                callback?.onError(code, errDesc)
            }
        })
    }

    /**
     * 安全隐藏控件
     *
     * @param views
     */
    fun gone(vararg views: View) {
        if (views != null && views.size > 0) {
            for (view in views) {
                if (view != null) {
                    view.visibility = View.GONE
                }
            }
        }
    }

    @Synchronized
    private fun showReadBar() { // 显示工具栏
        showSystemBar()
        visible(llBookReadBottom, read_abl_top_menu)
        val animation = AnimationUtils.loadAnimation(llBookReadBottom.getContext(), R.anim.push_bottom_in)
        llBookReadBottom.startAnimation(animation)
        val animation1 = AnimationUtils.loadAnimation(llBookReadBottom.getContext(), R.anim.push_top_in)
        read_abl_top_menu.startAnimation(animation1)
    }

    @Synchronized
    fun toggleReadBar(hideSystembar: Boolean) { // 切换工具栏 隐藏/显示 状态
        if (isVisible(read_abl_top_menu)) {
            hideReadBar(hideSystembar)
        } else {
            showReadBar()
        }
    }

    @Synchronized
    private fun hideReadBar() {
        hideReadBar(false)
    }

    @Synchronized
    fun hideReadBar(hideSystembar: Boolean) {
        llBookReadBottom.clearCheck()
        if (isVisible(rlReadAaSet)) {
            gone(rlReadAaSet)
            animInOrOut(rlReadAaSet, false)
            return
        }
        if (isVisible(rlReadMark)) {
            gone(rlReadMark)
            animInOrOut(rlReadMark, false)
            return
        }
        if (isVisible(read_brightness_set)) {
            gone(read_brightness_set)
            animInOrOut(read_brightness_set, false)
            return
        }
        if (isVisible(read_progress_set)) {
            gone(read_progress_set)
            animInOrOut(read_progress_set, false)
            gone(chapter_progress_container)
            return
        }
        if (hideSystembar) {
            hideSystemBar()
        }
        if (isGone(read_abl_top_menu)) {
            return
        }
        val isVisibleBottom = isVisible(llBookReadBottom)
        gone(rlReadAaSet, rlReadMark, llBookReadBottom, read_abl_top_menu)
        if (isVisibleBottom) {
            val animation = AnimationUtils.loadAnimation(llBookReadBottom.getContext(), R.anim.push_bottom_out)
            llBookReadBottom.startAnimation(animation)
        }
        val animation1 = AnimationUtils.loadAnimation(llBookReadBottom.getContext(), R.anim.push_top_out)
        read_abl_top_menu.startAnimation(animation1)
        // 清除选中状态
        llBookReadBottom.clearCheck()
    }

    private fun animInOrOut(view: View, inOrOut: Boolean) {
        if (RomUtils.isSmartisan()) {
            return
        }
        val animation = AnimationUtils.loadAnimation(view.context, if (inOrOut) R.anim.tran_next_in else R.anim.tran_next_out)
        view.startAnimation(animation)
    }

    /**
     * 注册相关
     */
    // 接收电池信息和时间更新的广播
    private val mReceiver = object : BroadcastReceiver() {
        private var mOldBattery = 0  // 旧的电量信息

        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == Intent.ACTION_BATTERY_CHANGED) {
                val level = intent.getIntExtra("level", 0)
                if (Math.abs(mOldBattery - level) > 4 || level == 100) { // 电量改变超过5% 才刷新一次
                    mOldBattery = level
                    if (mPageLoader != null) {
                        updateBattery(level)
                    }
                }
            } else if (intent.action == Intent.ACTION_TIME_TICK) {
                updateTime()
            } else if (ConnectivityManager.CONNECTIVITY_ACTION == intent.action) {
                // 监听网络状况

            }// 监听分钟的变化
        }
    }


    fun updateBattery(level: Int) {

    }

    fun updateTime() {

    }

    private fun register() {
        //注册广播
        val intentFilter = IntentFilter()
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED)
        intentFilter.addAction(Intent.ACTION_TIME_TICK)
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        registerReceiver(mReceiver, intentFilter)
        //eventbus register
        EventBus.getDefault().register(this)
        //监听屏幕亮度变化
        observeScreenLightness()
    }

    /**
     * 反注册相关
     */
    private fun unregister() {
        try {
            unregisterReceiver(mReceiver)
        } catch (e: Exception) {
        }

        EventBus.getDefault().unregister(this)
        contentResolver.unregisterContentObserver(mLightnessObserver)
    }

    override fun onDestroy() {
        AdUtils.destroyAd(adContainer)
        super.onDestroy()
        uploadReadTime(false)
        if (mReaderAdHelper != null) {
            mReaderAdHelper?.destroyAd()
            mReaderAdHelper = null
        }
        RxTimerUtils.cancel()
        mLifeCyclerSubject.onNext(ACTION_DESTORY)
        mHandler?.removeCallbacksAndMessages(null)
        mScreenOnHelper?.clear()
        mListPresenter?.detachView()
        unregister()
        // 发送页面退出广播
        EventBus.getDefault().post(ReaderFinishEvent())
        Utils.fixInputMethodManagerLeak(this)
        Utils.fixHwChangeWindowCtrlLeak()
        // 刷新书架数据
        refreshShelfData()
    }

    private class SafeHandler(context: Context) : Handler() {
        private val reference: WeakReference<Context>

        init {
            reference = WeakReference(context)
        }

    }

    private var mHandler: SafeHandler? = null
    private fun observeScreenLightness() {
        mHandler = SafeHandler(this)
        mLightnessObserver = object : ContentObserver(mHandler) {
            override fun onChange(selfChange: Boolean) {
                if (SettingManager.getInstance().isAutoBrightness) {
                    startAutoLightness()
                }
            }
        }
        contentResolver.registerContentObserver(
                Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS), true, mLightnessObserver)
    }

    private fun startAutoLightness() {
        SettingManager.getInstance().saveAutoBrightness(true)
        DisplayUtils.startAutoBrightness(this)
        val value = (DisplayUtils.getSystemBrightness(this) / 255f * 100).toInt()
        if (seekbarLightness != null) {
            seekbarLightness.setProgress(value)
        }
        DisplayUtils.setScreenBrightness(value, this)
        if (cbAutoBrightness != null) {
            cbAutoBrightness.setChecked(SettingManager.getInstance().isAutoBrightness)
        }
    }

    /**
     * 初始化阅读进度
     */
    private fun initReadProgress() {
        chapter_progress_bar.setMax(100)
        chapter_progress_bar.setOnSeekBarChangeListener(SeekBarChangeListener())
        val progress = SettingManager.getInstance().getCurReadProgress(mBookId)
        val count = SettingManager.getInstance().getChapterCount(mBookId)
        if (count > 0) {
            chapter_progress_bar.setProgress(progress.chapter * 100 / count)
        }
    }

    /**
     * 初始化顶部栏
     */
    private fun initTopMenu() {
        if (Build.VERSION.SDK_INT >= 19) {
            read_abl_top_menu.setPadding(0, DisplayUtils.getStatusBarHeight(this), 0, 0)
        }
    }

    /**
     * 初始化底部栏
     */
    private fun initBottomMenu() {
        //设置mBottomMenu的底部距离
        val params = llBookReadBottom.getLayoutParams() as ViewGroup.MarginLayoutParams
        params.bottomMargin = 0
        llBookReadBottom.setLayoutParams(params)
        // 显示导航栏
        SystemBarUtils.showStableNavBar(this)
        // 处理底部栏的点击事件
        handleBottomMenuClick()
    }

    /**
     * 处理底部栏的点击事件
     */
    private fun handleBottomMenuClick() {
        llBookReadBottom.setTabChangeCallback({ tabPos ->
            when (tabPos) {
                BookReadBottomLayout.TAB_READER_PROGRESS -> if (isVisible(llBookReadBottom)) {
                    if (isVisible(read_progress_set)) {
                        gone(read_progress_set)
                        animInOrOut(read_progress_set, false)
                        llBookReadBottom.clearCheck()
                    } else {
                        gone(rlReadAaSet, read_brightness_set, rlReadMark, chapter_progress_container)
                        calcReadProgress(mOrder)
                        visible(read_progress_set)
                        animInOrOut(read_progress_set, true)
                    }
                }
                BookReadBottomLayout.TAB_READER_BRIGHTNESS ->
                    // 亮度设置
                    if (isVisible(llBookReadBottom)) {
                        if (isVisible(read_brightness_set)) {
                            gone(read_brightness_set)
                            animInOrOut(read_brightness_set, false)
                            llBookReadBottom.clearCheck()
                        } else {
                            gone(rlReadAaSet, read_progress_set, rlReadMark)
                            visible(read_brightness_set)
                            animInOrOut(read_brightness_set, true)
                        }
                    }
                BookReadBottomLayout.TAB_READER_BOOKMARK ->
                    // 书签
                    if (isVisible(llBookReadBottom)) {
                        if (isVisible(rlReadMark)) {
                            gone(rlReadMark)
                            animInOrOut(rlReadMark, false)
                            llBookReadBottom.clearCheck()
                        } else {
                            gone(rlReadAaSet, read_progress_set, read_brightness_set)
                            updateMark()
                            visible(rlReadMark)
                            animInOrOut(rlReadMark, true)
                        }
                    }
                BookReadBottomLayout.TAB_READER_SETTINGS ->
                    // 字体设置
                    if (isVisible(llBookReadBottom)) {
                        if (isVisible(rlReadAaSet)) {
                            gone(rlReadAaSet)
                            animInOrOut(rlReadAaSet, false)
                            llBookReadBottom.clearCheck()
                        } else {
                            visible(rlReadAaSet)
                            gone(rlReadMark, read_progress_set, read_brightness_set)
                            animInOrOut(rlReadAaSet, true)
                        }
                    }
            }
        })
    }

    /**
     * 计算章节阅读进度
     *
     * @param chapterIndex
     */
    private fun calcReadProgress(chapterIndex: Int) {
        val chapterCount = mChapterSum
        if (chapterCount > 0) {
            chapter_progress_bar.setProgress(chapterIndex * 100 / chapterCount)
        }
    }

    /**
     * 初始化音量键开关展示
     */
    private fun initVolume() {
        val volumeFlipEnable = SettingManager.getInstance().isVolumeFlipEnable
        if (volumeFlipEnable) {
            volume_open.setChecked(true)
        } else {
            volume_close.setChecked(true)
        }
        volume_switch_container.setOnCheckedChangeListener({ group, checkedId ->
            if (checkedId == R.id.volume_open) {
                SettingManager.getInstance().saveVolumeFlipEnable(true)

            } else if (checkedId == R.id.volume_close) {
                SettingManager.getInstance().saveVolumeFlipEnable(false)

            }
        })
    }

    /**
     * 初始化屏幕常亮参数
     */
    private fun initScreenOnParams() {
        val param = SettingManager.getInstance().screenOnParam
        when (param) {
            BookConstants.ScreenOnParams.SCREEN_ON_3_MIN -> min_3.setChecked(true)
            BookConstants.ScreenOnParams.SCREEN_ON_5_MIN -> min_5.setChecked(true)
            BookConstants.ScreenOnParams.SCREEN_ON_10_MIN -> min_10.setChecked(true)
            BookConstants.ScreenOnParams.SCREEN_ON_OFTEN -> min_ofen.setChecked(true)
        }
        // 屏幕常亮参数设置
        screen_on_always_container.setOnCheckedChangeListener({ group, checkedId ->
            var mins = BookConstants.ScreenOnParams.SCREEN_ON_OFTEN
            if (checkedId == R.id.min_3) {
                mins = BookConstants.ScreenOnParams.SCREEN_ON_3_MIN

            } else if (checkedId == R.id.min_5) {
                mins = BookConstants.ScreenOnParams.SCREEN_ON_5_MIN

            } else if (checkedId == R.id.min_10) {
                mins = BookConstants.ScreenOnParams.SCREEN_ON_10_MIN

            } else if (checkedId == R.id.min_ofen) {
                mins = BookConstants.ScreenOnParams.SCREEN_ON_OFTEN

            } else {
            }
            SettingManager.getInstance().screenOnParam = mins
            mScreenOnHelper?.setScreenOnMins(mins)
        })
    }

    /**
     * 初始化主题
     */
    private fun initTheme() {
        ThemeManager.setAdHeight(mAdHeight)
        mCurTheme = SettingManager.getInstance().readTheme
        mReadThemes = ThemeManager.getReaderThemeData(mCurTheme)
        gvAdapter = ReadThemeAdapter(this, R.layout.item_read_theme, mReadThemes)
        gvTheme.setAdapter(gvAdapter)
        gvAdapter.setSelected(mCurTheme)
    }

    /**
     * 处理主题更换
     */
    private fun handleThemeChange() {
        gvTheme.setOnItemClickListener({ adapterView, view, pos, l ->
            if (pos >= mReadThemes.size || mPageLoader == null
                    || pos == gvAdapter.getSelected()) {
                return@setOnItemClickListener
            }
            gvAdapter.setSelected(pos)
            // 说明是夜间主题色
            if (pos == 5) {
                isNightMode = true
                setNightMode(isNightMode)
            } else {
                mCurTheme = pos
                if (isNightMode) {
                    setNightMode(false)
                    toggleNightModeUI()
                }
                setPageStyle(PageStyle.values()[pos])
            }
            toggleNightModeUI()
//            setAdBannerTheme()
        })
    }

    private fun setPageStyle(pageStyle: PageStyle) {
    }

    private fun setNightMode(isNightMode: Boolean) {

    }

    /**
     * 处理夜间和白天的UI
     */
    private fun toggleNightModeUI() {
        // 从本地文件中取值
        isNightMode = SettingManager.getInstance().isNight
        // 设置夜间模式UI
        night_mode.isChecked = isNightMode
        if (isNightMode) {
            if (gvAdapter != null) {
                // 设置为选中
                gvAdapter.selected = 5
            }
        }
    }

    /**
     * 初始化亮度
     */
    private fun initBrightness() {
        // 亮度调整
        seekbarLightness.setMax(100)
        seekbarLightness.setOnSeekBarChangeListener(SeekBarChangeListener())
        seekbarLightness.setProgress(SettingManager.getInstance().readBrightness)
        if (SettingManager.getInstance().isAutoBrightness) {
            startAutoLightness()
        } else {
            stopAutoLightness()
        }
        cbAutoBrightness.setOnCheckedChangeListener(ChechBoxChangeListener())
        cbAutoBrightness.setChecked(SettingManager.getInstance().isAutoBrightness)
        // 护眼模式
        eye_shield.setChecked(SettingManager.getInstance().isEyeShieldMode)
        eye_shield.setOnCheckedChangeListener(ChechBoxChangeListener())
        eye_shield_layout.setVisibility(if (SettingManager.getInstance().isEyeShieldMode) View.VISIBLE else View.GONE)
        // 夜间模式
        toggleNightModeUI()
        night_mode.setOnCheckedChangeListener(ChechBoxChangeListener())
    }

    private inner class SeekBarChangeListener : SeekBar.OnSeekBarChangeListener {
        private var mStartProgress: Boolean = false

        override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
            if (seekbarLightness != null && seekBar.id == seekbarLightness.getId() && fromUser) { // 非自动调节模式下 才可调整屏幕亮度
                stopAutoLightness()
                DisplayUtils.setScreenBrightness(progress, this@ReaderActivity)
                SettingManager.getInstance().saveReadBrightness(progress)
            } else if (chapter_progress_bar != null && seekBar.id == chapter_progress_bar.getId()) {
                Log.d("wcy", "start progress:" + seekBar.progress)
                if (seekBar.id == chapter_progress_bar.getId()) {
                    if (!mStartProgress) {
                        return
                    }
                    ObtainAllSimpleChaptersHelper.getAllSimpleChapters(mBookId, object : INetCommCallback<List<SimpleChapterBean>> {
                        override fun onResponse(list: List<SimpleChapterBean>) {
                            if (chapter_progress_container == null) {
                                return
                            }
                            if (!Utils.isEmptyList(list)) {
                                val progress = seekBar.progress
                                var chapter = progress * mChapterSum / 100
                                chapter = chapter - 1
                                if (chapter >= list.size) {
                                    chapter = list.size - 1
                                }
                                if (chapter >= mChapterSum) {
                                    chapter = mChapterSum - 1
                                }
                                if (chapter < 0) {
                                    chapter = 0
                                }
                                mSeekbarListenerPageCount = 0
                                DisplayUtils.visible(chapter_progress_container)
                                chapter_progress_name.setText(list[chapter].title)
                                chapter_progress_txt.setText(BookUtils.getReadProgress((if (chapter > 0) chapter + 1 else 0).toString(), mChapterSum.toString()))
                            }
                        }

                        override fun onError(code: Int, errDesc: String) {
                            DisplayUtils.gone(chapter_progress_container)
                        }
                    })
                }
            }
        }

        override fun onStartTrackingTouch(seekBar: SeekBar) {
            if (chapter_progress_bar != null && seekBar.id == chapter_progress_bar.getId()) {
                if (Utils.isEmptyList(ObtainAllSimpleChaptersHelper.getAllSimpleChaptersFromCache(mBookId))) {
                    var s = "正在加载章节数据，请稍后。"
                    if (getPageStatus() === PageLoader.STATUS_OFFLINE) {
                        s = "书籍已下线"
                    }
                    ToastUtil.showMessage(s)
                    mStartProgress = false
                    return
                }
                // 先隐藏掉之间衔接广告
//                DisplayUtils.gone(mAdBetweenChaptersLayout)
                mStartProgress = true
            }
        }

        override fun onStopTrackingTouch(seekBar: SeekBar) {
            if (chapter_progress_bar != null && seekBar.id == chapter_progress_bar.getId()) {
                mStartProgress = false
                // 处理阅读进度
                handleReadProgress(seekBar.progress)
            }
        }
    }

    /**
     * 处理拖动的进度
     */
    private fun handleReadProgress(progress: Int) {
        // 处理之前先隐藏掉菜单栏
        gone(read_abl_top_menu, llBookReadBottom, read_progress_set)
        hideSystemBar()
        ObtainAllSimpleChaptersHelper.getAllSimpleChapters(mBookId, object : INetCommCallback<List<SimpleChapterBean>> {
            override fun onResponse(list: List<SimpleChapterBean>) {
                if (Utils.isEmptyList(list) || mPageLoader == null) {
                    return
                }
                var chapter = progress * list.size / 100
                chapter = chapter - 1
                if (chapter >= list.size) {
                    chapter = list.size - 1
                }
                if (chapter < 0) {
                    chapter = 0
                }
                mChapterId = list[chapter].content_id
                if (list[chapter].order.matches(Regex("[0-9]*"))) {
                    mOrder = Integer.valueOf(list[chapter].order)
                } else {
                    mOrder = chapter + 1
                }
                mStartRead = false
                readCurrentChapter()
            }

            override fun onError(code: Int, errDesc: String) {

            }
        })
    }

    /**
     * 开始读取当前章内容
     */
    private fun readCurrentChapter() {
        prepareBook()
        readContentByNetOrLocal()
    }

    /**
     * 初始化书籍
     */
    private fun prepareBook() {
        // 获取阅读记录
        mBookRecord = SettingManager.getInstance().getCurReadProgress(mBookId)
        // 获取总章节数
        mChapterSum = SettingManager.getInstance().getChapterCount(mBookId)
        // 阅读记录获取
        if (mBookRecord == null) {
            mBookRecord = BookRecordBean()
            mBookRecord!!.setBookId(mBookId)
        }
        mOrder = mBookRecord!!.getChapter()
        mTopItemPos = mBookRecord!!.getItemPos()
        mChapterNode = getSimpleChapterBean(mOrder)
    }

    fun saveRecord() {
        mBookRecord?.let {
            it.setBookId(mBookId)
            it.setChapter(mRecordOrder)
            it.setItemPos(mTopItemPos)
            //TODO save scroll position
//            if (mCurPage != null) {
//                mBookRecord.setPagePos(mCurPage.position)
//            } else {
//                mBookRecord.setPagePos(0)
//            }
            //存储到数据库
            SettingManager.getInstance().saveReadProgress(mBookRecord)
        }

    }

    private fun setCurChapterPos(pos: Int) {
        mOrder = pos
    }

    private fun stopAutoLightness() {
        SettingManager.getInstance().saveAutoBrightness(false)
        DisplayUtils.stopAutoBrightness(this)
        val value = SettingManager.getInstance().readBrightness
        if (seekbarLightness != null) {
            seekbarLightness.setProgress(value)
        }
        DisplayUtils.setScreenBrightness(value, this@ReaderActivity)
        if (cbAutoBrightness != null) {
            cbAutoBrightness.setChecked(SettingManager.getInstance().isAutoBrightness)
        }
    }

    private inner class ChechBoxChangeListener : CompoundButton.OnCheckedChangeListener {
        override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
            if (buttonView.id == cbAutoBrightness.getId()) {
                // 修改亮度
                if (isChecked) {
                    startAutoLightness()
                } else {
                    stopAutoLightness()
                }
            } else if (buttonView.id == eye_shield.getId()) {
                // 护眼模式
                SettingManager.getInstance().isEyeShieldMode = isChecked
                eye_shield_layout.setVisibility(if (isChecked) View.VISIBLE else View.GONE)
            } else if (buttonView.id == night_mode.getId()) {
                isNightMode = isChecked
                processClickDayNight()
            }
        }
    }

    /**
     * 处理点击夜间和白天模式
     */
    private fun processClickDayNight() {
        if (isNightMode) {
            setNightMode(true)
            if (gvAdapter != null) {
                // 设置为选中
                gvAdapter.selected = 5
            }
        } else {
            setNightMode(false)
            val pos = SettingManager.getInstance().readTheme
            setPageStyle(PageStyle.values()[pos])
            if (gvAdapter != null) {
                gvAdapter.selected = mCurTheme
            }
        }
        // 设置底部banner背景色
//        setAdBannerTheme()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun handleShelfEvent(event: ShelfEvent) {
        when (event.code) {
            ShelfEvent.ADD_TO_SHELF_SUCCESS -> ToastUtil.showMessage("加入书架成功")
            else -> {
            }
        }
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
        llBookReadBottom.clearCheck()
        when (keyCode) {
            KeyEvent.KEYCODE_BACK -> if (isVisible(rlReadAaSet)) {
                gone(rlReadAaSet)
                animInOrOut(rlReadAaSet, false)
                return true
            } else if (isVisible(rlReadMark)) {
                gone(rlReadMark)
                animInOrOut(rlReadMark, false)
                return true
            } else if (isVisible(read_progress_set)) {
                gone(read_progress_set)
                animInOrOut(read_progress_set, false)
                return true
            } else if (isVisible(read_brightness_set)) {
                gone(read_brightness_set)
                animInOrOut(read_brightness_set, false)
                return true
            } else if (isVisible(read_abl_top_menu)) {
                hideSystemBar()
                val isVisibleBottom = isVisible(llBookReadBottom)
                // 顶部菜单栏
                gone(read_abl_top_menu, llBookReadBottom)
                if (isVisibleBottom) {
                    val animation = AnimationUtils.loadAnimation(llBookReadBottom.getContext(), R.anim.push_bottom_out)
                    llBookReadBottom.startAnimation(animation)
                }
                val animation1 = AnimationUtils.loadAnimation(llBookReadBottom.getContext(), R.anim.push_top_out)
                read_abl_top_menu.startAnimation(animation1)
                return true
            } else {
                // 处理加入书架
                val code = processJoinShelf()
                if (code == 0) {
                    // 看看是不是要跳转到主页面
                    Utils.jumpToHomeIfNeed()
                    return super.onKeyUp(keyCode, event)
                }
                return true
            }
            KeyEvent.KEYCODE_MENU -> {
                toggleReadBar(true)
                return true
            }
            else -> {
            }
        }
        return super.onKeyUp(keyCode, event)
    }

    /**
     * 处理是否添加到书架
     *
     * @return 0 已经加入书架 1没有加入书架
     */
    private fun processJoinShelf(): Int {
        // 刷新最近阅读信息
        val event = ShelfEvent(ShelfEvent.REFRESH_RECENT)
        event.obj = mBookId
        EventBus.getDefault().post(event)
        var flg = false
        var bookInfos = SettingManager.getInstance().shelfInfos
        if (Utils.isEmptyList(bookInfos)) {
            bookInfos = SettingManager.getInstance().shelfInfosFromSd
        }
        if (!Utils.isEmptyList(bookInfos)) {
            for (bookInfo in bookInfos) {
                if (TextUtils.equals(mBookId, bookInfo.book_id)) {
                    flg = true
                    break
                }
            }
        }
        if (flg || mJoinShelfFromServer) {
            return 0
        }
        CustomDialog.show(this, "加入收藏", "是否将本书加入我的收藏", object : CustomDialog.Callback {
            override fun onSure(dialog: Dialog?) {
                if (dialog == null) {
                    return
                }
                dialog.dismiss()
                val bookPresenter = BookPresenter(null)
                bookPresenter.joinBookShelf(mBookId)
                finish()
            }

            override fun onCancel(dialog: Dialog?) {
                if (dialog != null && !isFinishing) {
                    dialog.dismiss()
                    finish()
                }
            }
        }, false, "下次再说", "加入收藏")
        return 1
    }

    override fun processLogic() {
        super.processLogic()
        // 改变书籍状态(更新标记)
        AndroidSchedulers.mainThread().scheduleDirect({
            val event = ShelfEvent(ShelfEvent.UPDATE_BOOK_STATUS)
            event.obj = mBookId
            EventBus.getDefault().post(event)
        }, 1200, TimeUnit.MILLISECONDS)
        // 定时上报逻辑打开
        if (ARouter.getInstance().navigation(IMakeMoneyService::class.java) != null) {
            ARouter.getInstance().navigation(IMakeMoneyService::class.java).activateStatisticsService()
        }
        // 开始阅读小说
        processRead()
    }

    /**
     * 开始阅读
     */
    private fun processRead() {
        if (TextUtils.isEmpty(mBookId)) {
            return
        }
        // 开始阅读小说
        readCurrentChapter()
    }

    /**
     * 获取当前页的状态
     *
     * @return
     */
    fun getPageStatus(): Int {
        return mStatus
    }

    /**
     * 隐藏阅读界面的菜单显示
     *
     * @return 是否隐藏成功
     */
    private fun hideReadMenu(): Boolean {
        llBookReadBottom.clearCheck()
        if (isVisible(read_progress_set)) {
            gone(read_progress_set)
            animInOrOut(read_progress_set, false)
            return true
        }
        if (isVisible(read_brightness_set)) {
            gone(read_brightness_set)
            animInOrOut(read_brightness_set, false)
            return true
        }
        if (isVisible(rlReadAaSet)) {
            gone(rlReadAaSet)
            animInOrOut(rlReadAaSet, false)
            return true
        }
        if (isVisible(rlReadMark)) {
            gone(rlReadMark)
            animInOrOut(rlReadMark, false)
            return true
        }
        hideSystemBar()
        if (isVisible(read_abl_top_menu)) {
            toggleReadBar(true)
            return true
        }
        return false
    }

    /**
     * 获取简单章节参数信息
     *
     * @param order
     * @return
     */
    fun getSimpleChapterBean(order: Int): SimpleChapterBean? {
        return SettingManager.getInstance().getSimpleChapterInfo(mBookId, order)
    }

    /**
     * 根据章节序号获取章节内容
     *
     * @param order
     * @return
     */
    fun getTxtChapter(order: Int): TxtChapter? {
        val bean = getSimpleChapterBean(order)
        if (bean != null) {
            val chapter = TxtChapter.obtain()
            chapter.bookId = mBookId
            chapter.chapterIndex = order
            chapter.title = bean.title
            return chapter
        }
        return null
    }

    fun getBookTitle(): String? {
        if (!TextUtils.isEmpty(mBookTitle)) {
            return mBookTitle
        }
        val bean = getSimpleChapterBean(mOrder)
        if (bean != null) {
            mBookTitle = bean.book_title
        }
        if (TextUtils.isEmpty(mBookTitle)) {
            val item = DiskLruCacheUtils.get(mBookId + "simple", ChapterBean.BookInfoBean::class.java)
            if (item != null) {
                mBookTitle = item.book_title
            }
        }
        // 兼容之前的老数据
        if (TextUtils.isEmpty(mBookTitle)) {
            if (TextUtils.isEmpty(mBookTitle)) {
                mBookTitle = SettingManager.getInstance().getCurBookTitle(mBookId, mOrder)
            }
        }
        return mBookTitle
    }

    /**
     * 设置扉页信息
     *
     * @param entity
     */
    // 扉页信息
    private var mCpEntity: CpEntity? = null

    fun setHeadpageInfo(entity: CpEntity) {
        mCpEntity = entity
        // 将信息保存在本地,以便断网的时候显示
        DiskLruCacheUtils.put("$mBookId@cp_info", entity, true)
    }

    /**
     * 上传阅读章节时间
     *
     * @param isEnd 是否是章节尾页
     */
    private fun uploadReadTime(isEnd: Boolean) {
        if (mOldTime != 0L && !TextUtils.isEmpty(mCurrentChapterPos)) {
            var consuming = System.currentTimeMillis() - mOldTime
            if (consuming > -1 && consuming < 1000) {
                return
            }
            if (isEnd) {
                consuming += consuming / (mCurrentChapterCount - 1) / 2 // 最后一页阅读时间加前面的平均值
            }
            Log.d("upLoadUserReadaction", "consuming: $consuming")
            if (consuming < 0) {
                consuming = (20 * 60 * 1000).toLong()
            } else if (consuming < 2000) { // 最低2秒钟
                consuming = (2 * 1000).toLong()
            }
            mPresenter.upLoadUserReadaction(mBookId, mCurrentChapterPos, mCurrentChapterCount, consuming)
            if (isEnd) {
                mOldTime = 0
            }
        }
    }

    /**
     * 刷新最近阅读数据(最近阅读)
     */
    private fun refreshShelfData() {
        // 刷新最近阅读信息
        val event = ShelfEvent(ShelfEvent.REFRESH_RECENT)
        EventBus.getDefault().post(event)
    }

    /**
     * 下载上一章和下一章的章节内容
     *
     * @param chapter
     */
    private fun downLastAndNextContent(chapter: Int) {
        val info = SettingManager.getInstance().getSimpleChapterInfo(mBookId, chapter)
        // 如果存在文件才去缓存上一章和下一章数据
        if (info != null) {
            // 预加载上一章和下一章的数据
            // 获取当前章节内容id
            mChapterId = info.content_id
            val next_content_id = info.next_content_id
            if (!TextUtils.isEmpty(info.next_order)) {
                // 预先加载下一章
                val nextChapterIndex = Integer.parseInt(info.next_order)
                if (!TextUtils.isEmpty(next_content_id) && CacheManager.getInstance().getChapterFile(mBookId, nextChapterIndex) == null) {
                    getChapterContent(next_content_id, ChapterRequestParams.CACHED, LOAD_TYPE_NEXT)
                    downloadSimpleChapter(nextChapterIndex)
                }
            }
            // 预先加载上一章
            val last_content_id = info.last_content_id
            if (!TextUtils.isEmpty(info.last_order) && !TextUtils.isEmpty(info.last_order)) {
                val lastChapterIndex = Integer.parseInt(info.last_order)
                if (!TextUtils.isEmpty(last_content_id) && lastChapterIndex > 0 && CacheManager.getInstance().getChapterFile(mBookId, lastChapterIndex) == null) {
                    getChapterContent(last_content_id, ChapterRequestParams.CACHED, LOAD_TYPE_LAST)
                    downloadSimpleChapter(lastChapterIndex)
                }
            }
        } else {
            // 预下载 简单章节信息
            downloadSimpleChapter(chapter, object : INetCommCallback<SimpleChapterBean> {
                override fun onResponse(infoFromNet: SimpleChapterBean?) {
                    if (infoFromNet != null) {
                        // 预加载上一章和下一章的数据
                        // 获取当前章节内容id
                        mChapterId = infoFromNet.content_id
                        val next_content_id = infoFromNet.next_content_id
                        if (!TextUtils.isEmpty(infoFromNet.next_order)) {
                            // 预先加载下一章
                            val nextChapterIndex = Integer.parseInt(infoFromNet.next_order)
                            if (!TextUtils.isEmpty(next_content_id) && CacheManager.getInstance().getChapterFile(mBookId, nextChapterIndex) == null) {
                                getChapterContent(next_content_id, ChapterRequestParams.CACHED, LOAD_TYPE_NEXT)
                            }
                        }
                        // 预先加载上一章
                        val last_content_id = infoFromNet.last_content_id
                        if (!TextUtils.isEmpty(infoFromNet.last_order) && !TextUtils.isEmpty(infoFromNet.last_order)) {
                            val lastChapterIndex = Integer.parseInt(infoFromNet.last_order)
                            if (!TextUtils.isEmpty(last_content_id) && lastChapterIndex > 0 && CacheManager.getInstance().getChapterFile(mBookId, lastChapterIndex) == null) {
                                getChapterContent(last_content_id, ChapterRequestParams.CACHED, LOAD_TYPE_LAST)
                            }
                        }
                    }
                }

                override fun onError(code: Int, errDesc: String?) {

                }

            })
        }
    }

    fun preloadLastAndNext(loadByLocal: Boolean) {
        downLastAndNextContent(mOrder)
        if (loadByLocal)
            mPageLoader.post(Runnable { loadLastAndNextByLocal() })
    }

    var loadingData = false
    fun loadLastAndNextByLocal() {
        // 预先加载下一章
        loadNextByLocal()
        // 预先加载上一章
        loadLastByLocal()
    }

    fun loadNextByLocal() {
        // 本地加载下一章
        var nextOrderStr = mChapterNode?.next_order
        if (!TextUtils.isEmpty(nextOrderStr)) {
            val nextChapterIndex = Integer.parseInt(nextOrderStr)
            if (!TextUtils.isEmpty(mChapterNode?.next_content_id) && CacheManager.getInstance().getChapterFile(mBookId, nextChapterIndex) != null) {
                loadChapter(nextChapterIndex, LOAD_TYPE_NEXT)
            }
        }
    }

    fun loadLastByLocal() {
        // 本地加载上一章
        var lastOrderStr = mChapterNode?.last_order
        if (!TextUtils.isEmpty(lastOrderStr)) {
            val lastChapterIndex = Integer.parseInt(lastOrderStr)
            if (!TextUtils.isEmpty(mChapterNode?.last_content_id) && CacheManager.getInstance().getChapterFile(mBookId, lastChapterIndex) != null) {
                loadChapter(lastChapterIndex, LOAD_TYPE_LAST)
            }
        }
    }

    var isUpdating = false
    fun updateOrder(order: Int) {
        if (isUpdating) {
            return
        }
        isUpdating = true
        if (order > mOrder) {
            //向下滑动
            if (mNextChapterNode != null) {
                //删除上一章内容
                if (mLastChapterNode != null) {
                    var listRemoved = mutableListOf<ReaderItem>()
                    if (data.size > 0) {
                        for (item in data) {
                            if (item.order <= mLastChapterNode!!.order.toInt()) {
                                listRemoved.add(item)
                            } else {
                                break
                            }
                        }
                        data.removeAll(listRemoved)
                        readerAdapter.notifyItemRangeRemoved(0, listRemoved.size)
                    }
                }
                //当前章作为上一章,下一章作为当前章
                mLastChapterNode = mChapterNode
                mChapterNode = mNextChapterNode
                mOrder = mChapterNode!!.order.toInt()
                if (!TextUtils.isEmpty(mChapterNode!!.next_order)) {
                    mNextChapterNode = getSimpleChapterBean(mChapterNode!!.next_order!!.toInt())
                } else {
                    mNextChapterNode = null
                }
                loadNextByLocal()
            }
        } else if (order < mOrder) {
            //向上滑动
            if (mLastChapterNode != null) {
                //删除下一章内容
                if (mNextChapterNode != null) {
                    var size = data.size
                    var listRemoved = mutableListOf<ReaderItem>()
                    for (item in data) {
                        if (item.order >= mNextChapterNode!!.order.toInt()) {
                            listRemoved.add(item)
                        }
                    }
                    data.removeAll(listRemoved)
                    readerAdapter.notifyDataSetChanged()
//                    readerAdapter.notifyItemRangeRemoved(size - listRemoved.size, size)
                }
                //当前章作为下一章,上一章作为当前章
                mNextChapterNode = mChapterNode
                mChapterNode = mLastChapterNode
                mOrder = mChapterNode!!.order.toInt()
                if (!TextUtils.isEmpty(mChapterNode!!.last_order)) {
                    mLastChapterNode = getSimpleChapterBean(mChapterNode!!.last_order!!.toInt())
                } else {
                    mLastChapterNode = null
                }
            }
            loadLastByLocal()
        }
        mOrder = order
        updateTitleInfo()
        isUpdating = false
        preloadLastAndNext(false)
    }

    override fun onPause() {
        super.onPause()
        saveRecord()
    }
}
